package threads;

import java.util.Scanner;

public class StoppingThread extends Thread {

	public void run() {
		int counter = 0;
		try {
			while (! isInterrupted()) {
				Thread.sleep(1000);
				System.out.printf("thread: Running: %d sec.\n", counter);
				counter++;
			}
		} catch (InterruptedException e) {
			System.out.println("thread: Catched interrupted exception.");
		} finally {
			System.out.println("thread: Finally block.");
		}
		System.out.println("thread: Thread finished.");
	}

	public static void main(String[] args) {
		StoppingThread thread = new StoppingThread();
		thread.start();
		
		Scanner console = new Scanner(System.in);
		while (true) {
			System.out.println("main: Enter 'stop' for stopping the thread");
			String line = console.nextLine();
			if (line.equals("stop")) {
				thread.interrupt();
				System.out.println("main: Sent interrupt request the thread.");
			} else {
				System.out.println("main: Unknown command.");
			}
		}
	}

}
